﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

using ComiKamiQ;

namespace ComiKamiQ3
{
    public partial class ComiDownForm : Form
    {
        private DUtil dutil;
        private string tasks;
        //private TreeNode downloadingNode;
        //private Page downloadingPage;
        private WebClient client=new WebClient();
        private IList<Page> taskList;
        private IEnumerator<Page> iterator=null;

        private string version;
        private int subversion=13;
        private bool isSvnEdition = true;

        public ComiDownForm()
        {
            InitializeComponent();
            int lastDotIndex = Application.ProductVersion.LastIndexOf('.');
            this.version = "v" + Application.ProductVersion.Substring(0,lastDotIndex);

            string version = this.version;
            if (isSvnEdition) version += "(SVN r" + subversion + ")";
            else version += "(" + Application.ProductVersion.Substring(lastDotIndex+1) + ")";
            this.Text += " "+version;
            tasks = null;
        }
        public String Tasks
        {
            get { return tasks; }
        }

        #region 初始化
        private void ComiDownForm_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("没有章节目录");
            comboBox1.Items.Add("章节名");
            comboBox1.Items.Add("章节序号");
            comboBox1.Items.Add("章节序号_章节名(*)");
            comboBox1.SelectedIndex = 3;

            comboBox2.Items.Add("章节序号_页码");
            comboBox2.Items.Add("原文件名");
            comboBox2.Items.Add("页码(*)");
            comboBox2.Items.Add("页码_原文件名");
            comboBox2.Items.Add("章节序号_页码_原文件名");
            comboBox2.SelectedIndex = 2;
            
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);

            //progressBar1.Minimum = 0;
            //progressBar1.Maximum = 100;
            txtURL.Text = "http://manhua.178.com/jiasushijie/";
            txtRoot.Text = @"D:\comic\ckqtest\KasokuSekai";
        }
        #endregion

        #region 按钮事件
        private void btnOpen_Click(object sender, EventArgs e)
        {
            dutil = new DUtil178(txtURL.Text);
            try
            {
                dutil.SpiderChapters();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"错误");
            }
            treeView1.Nodes.Clear();
            checkedListBox1.Items.Clear();
            foreach (Chapter chapter in dutil.Chapters)
            {
                checkedListBox1.Items.Add(chapter);
            }
            tabControl1.SelectedIndex = 0;
        }

        private void btnAnalysis_Click(object sender, EventArgs e)
        {
            if (dutil == null) return;
            if (txtRoot.Text == "")
            {
                MessageBox.Show("下载目录未设置","错误");
                return;
            }
            dutil.Root = txtRoot.Text;
            dutil.ChapterNameConfig = comboBox1.SelectedIndex;
            dutil.PageNameConfig = comboBox2.SelectedIndex;
            //设置选取
            foreach (Chapter chapter in dutil.Chapters)
            {
                chapter.Checked = false;
            }
            foreach (Chapter chapter in checkedListBox1.CheckedItems)
            {
                chapter.Checked = true;
                dutil.SpiderPages(chapter);
            }
            dutil.SetPathForAllPage(true);
            //清空原有的节点映射
            treeView1.Nodes.Clear();
            foreach (Chapter chapter in dutil.Chapters)
            {
                chapter.Tag = null;
                foreach (Page page in chapter.Pages)
                    page.Tag = null;
            }
            taskList = new List<Page>();
            //重新建立节点树
            foreach (Chapter chapter in dutil.Chapters)
            {
                if (!chapter.Checked) continue;
                TreeNode node = treeView1.Nodes.Add(chapter.ToString());
                node.Tag = chapter;
                chapter.Tag = node;
                foreach (Page page in chapter.Pages)
                {
                    TreeNode subNode = node.Nodes.Add(page.ToString());
                    subNode.Tag = page;
                    page.Tag = subNode;
                    taskList.Add(page);
                }
            }
            tabControl1.SelectedIndex=1;
            iterator = taskList.GetEnumerator();
        }

        private void btnSelectReverse_Click(object sender, EventArgs e)
        {
            int i, count = checkedListBox1.Items.Count;
            for (i = 0; i < count; i++)
                checkedListBox1.SetItemChecked(i, !checkedListBox1.GetItemChecked(i));
        }

        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            int i, count = checkedListBox1.Items.Count;
            for (i = 0; i < count; i++)
                checkedListBox1.SetItemChecked(i, true);
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (iterator == null) return;
            if (ControlsEnable)//btnDownload.Text == "开始下载"
            {
                //其他按钮全部禁用掉
                ControlsEnable = false;
                downloadNextPage();
            }
            else
            {
                client.CancelAsync();
                //启用按钮
                ControlsEnable = true;
            }
        }

        private void btnChooseDir_Click(object sender, EventArgs e)
        {
            DialogResult dr = folderBrowserDialog1.ShowDialog();
            if (dr != DialogResult.OK)
                return;
            txtRoot.Text = folderBrowserDialog1.SelectedPath;
        }

        #endregion

        public bool ControlsEnable
        {
            get 
            {
                //return client.IsBusy;
                return btnDownload.Text=="开始下载"; 
            }
            set
            {
                if (value) //结束或者暂停
                {
                    btnAnalysis.Enabled = true;
                    btnChooseDir.Enabled = true;
                    btnOpen.Enabled = true;
                    btnSelectAll.Enabled = true;
                    btnSelectReverse.Enabled = true;
                    btnDownload.Text = "开始下载";
                    lblDownloadingFileName.Text = "任务完成";
                    foreach (Chapter chapter in dutil.Chapters)
                    {
                        if (chapter.Tag != null)
                        {
                            TreeNode node = (TreeNode)chapter.Tag;
                            node.Text = chapter.ToString();
                        }
                    }
                }
                else
                {
                    btnAnalysis.Enabled = false;
                    btnChooseDir.Enabled = false;
                    btnOpen.Enabled = false;
                    btnSelectAll.Enabled = false;
                    btnSelectReverse.Enabled = false;
                    btnDownload.Text = "停止下载";
                    lblDownloadingFileName.Text = "正在开始下载...";
                }
            }
        }

        private void downloadNextPage()
        {
            bool endOfList=!iterator.MoveNext();
            if (endOfList)
            {
                ControlsEnable = true;
                return;
            }
            downloadPage(iterator.Current);
        }

        private bool downloadPage(Page page)
        {
            //4种情况下跳到下个任务: 
            //0.任务失败 
            //1.任务已完成（已经标记为下载完毕或者文件已存在） 
            //2.Page不存在 
            //3.引发了无法建立目录异常
            //Page不存在
            if (page == null)
            {
                downloadNextPage();
                return false;
            }
            //Page已经标记为Downloaded
            page.Chapter.Started = true;
            if (page.Downloaded)
                downloadNextPage();
            //文件已存在
            if (File.Exists(page.Path))
            {
                pageDownloadCompleted(page);//标记下载完成
                downloadNextPage();
                return false;
            }
            //建立下载目录
            string pathWithoutFileName = page.GetPathWithoutFileName();
            if (!Directory.Exists(pathWithoutFileName))
            {
                try
                {
                    Directory.CreateDirectory(pathWithoutFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误");
                    downloadNextPage();
                    return false;
                }
            }
            //开始异步下载文件
            try
            {
                client.DownloadFileAsync(new Uri(page.Url), page.Path + ".tmp");
            }
            catch (Exception ex)
            {
                File.Delete(page.Path + ".tmp");
                MessageBox.Show("任务停止：" + ex.Message);
            }
            progressBar1.Value = 0;
            return true;
        }

        #region 下载事件
        private void pageDownloadCompleted(Page page)
        {
            page.Downloaded = true;
            //更新页节点
            ((TreeNode)page.Tag).Text = page.ToString();
            //更新章节点
            Chapter chapter = page.Chapter;
            ((TreeNode)chapter.Tag).Text = chapter.ToString();
        }

        /// <summary>
        /// 当前正在下载的文件完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void client_DownloadFileCompleted(Object sender, AsyncCompletedEventArgs e)
        {
            Page downloadingPage = iterator.Current;
            //正常的下载完成，有临时文件存在
            string fileTempPath = downloadingPage.Path + ".tmp";
            File.Copy(fileTempPath, downloadingPage.Path, true);
            File.Delete(fileTempPath);
            pageDownloadCompleted(downloadingPage);
            downloadNextPage();
        }

        private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Page downloadingPage = iterator.Current;
            Chapter downloadingChapter = downloadingPage.Chapter;
            lblDownloadingFileName.Text = "正在下载 " + downloadingChapter.Name + "第" + downloadingPage.Index+ "页：" + e.ProgressPercentage + "%";
            progressBar1.Value = e.ProgressPercentage;
        }
        #endregion

    }
}
